package com.vv.ossupload.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:aws-oss-${spring.profiles.active}.properties")
public class OssConfig {

    @Value("${aws-oss.endpoint}")
    private String endpoint;

    @Value("${aws-oss.accessKeyId}")
    private String accessKey;

    @Value("${aws-oss.accessKeySecret}")
    private String secretKey;

    // XEOS对region没有要求，任何字符串都可以
    String region = "";


    @Bean
    public AmazonS3 amazonS3() {
        AmazonS3ClientBuilder builder = AmazonS3Client.builder();
        builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region));
        builder.setCredentials(new AWSStaticCredentialsProvider(new
                BasicAWSCredentials(accessKey, secretKey)));
        builder.setClientConfiguration(clientConfiguration());
        builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region));
        return builder.build();
    }


    @Bean
    public ClientConfiguration clientConfiguration() {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // 标识是否允许 expect continue ⽅式。推荐 false
        clientConfiguration.setUseExpectContinue(false);
        // 申明使⽤http 或者 https
        clientConfiguration.setProtocol(Protocol.HTTP);
        // 使⽤V2(S3SignerType) 或者 V4(AWSS3V4SignerType) 签名，默认
        clientConfiguration.setSignerOverride("S3SignerType");
        // 设置重试次数，针对 5xx 重试，默认-1 不重试
        clientConfiguration.setMaxErrorRetry(3);
        // 连接池最⼤连接数，默认 50 个
        clientConfiguration.setMaxConnections(50);
        // 请求执⾏超时时间，默认为 0 （关闭超时）。
        clientConfiguration.setClientExecutionTimeout(0);
        // 创建新连接超时时间，默认 10s
        clientConfiguration.setConnectionTimeout(10 * 10000);
        // 连接处于 idle 状态的时间(空闲状态)，默认 60s。
        clientConfiguration.setConnectionMaxIdleMillis(60 * 1000);
        // 连接池中连接的默认过期时间，默认-1 （关闭过期）
        clientConfiguration.setConnectionTTL(-1);
        return clientConfiguration;
    }
}